package com.enjoylearning.content.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enjoylearning.base.exception.XueChengPlusException;
import com.enjoylearning.content.mapper.*;
import com.enjoylearning.content.model.dto.AddCourseDto;
import com.enjoylearning.content.model.dto.CourseBaseInfoDto;
import com.enjoylearning.content.model.dto.EditCourseDto;
import com.enjoylearning.content.model.po.*;
import com.enjoylearning.content.service.CourseBaseInfoService;
import com.enjoylearning.base.model.PageParams;
import com.enjoylearning.base.model.PageResult;
import com.enjoylearning.content.model.dto.QueryCourseParamsDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    private final CourseBaseMapper courseBaseMapper;

    private final CourseMarketMapper courseMarketMapper;

    private final CourseCategoryMapper courseCategoryMapper;

    private final TeachplanMapper teachplanMapper;

    private final TeachplanMediaMapper teachplanMediaMapper;

    private final CourseTeacherMapper courseTeacherMapper;
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long comoanyId,PageParams pageParams, QueryCourseParamsDto courseParamsDto) {
        //拼装查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //根据名称模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(courseParamsDto.getCourseName()),CourseBase::getName,courseParamsDto.getCourseName());
        //根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,courseParamsDto.getAuditStatus());
        //根据课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDto.getPublishStatus()), CourseBase::getStatus,courseParamsDto.getPublishStatus());
        //根据机构id查询
        queryWrapper.eq(comoanyId != null,CourseBase::getCompanyId,comoanyId);
        //创建分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(),pageParams.getPageSize());
        //分页查询
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page,queryWrapper);
        //构建返回结果
        PageResult<CourseBase> result = new PageResult<>(pageResult.getRecords(), pageResult.getTotal(), pageParams.getPageNo(), pageParams.getPageSize());
        return result;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId,AddCourseDto addCourseDto) {
        //参数的合法性校验
//        if (StringUtils.isBlank(addCourseDto.getName())) {
//            throw new RuntimeException("课程名称为空");
//            XueChengPlusException.cast("课程名称为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getMt())) {
//            XueChengPlusException.cast("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getSt())) {
//            XueChengPlusException.cast("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getGrade())) {
//            XueChengPlusException.cast("课程等级为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getTeachmode())) {
//            XueChengPlusException.cast("教育模式为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getUsers())) {
//            XueChengPlusException.cast("适应人群为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getCharge())) {
//            XueChengPlusException.cast("收费规则为空");
//        }

        //向课程信息表Course_base添加数据
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto,courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        //设置为默认未提交
        courseBase.setAuditStatus("202002");
        courseBase.setStatus("203001");
        int insert = courseBaseMapper.insert(courseBase);
        if (insert <= 0){
            throw new RuntimeException("添加课程失败");
        }
        //向课程营销表Course_market添加信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        courseMarket.setId(courseBase.getId());
        //保存营销信息
        saveCourseMarket(courseMarket);
        //从数据库查询课程的详细信息，包括两部分
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseBase.getId());
        return courseBaseInfo;
    }

    @Override
    public CourseBaseInfoDto selectById(Long id) {
        CourseBase courseBase = courseBaseMapper.selectById(id);
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        CourseCategory st = courseCategoryMapper.selectById(courseBase.getSt());
        CourseCategory mt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(mt.getName());
        courseBaseInfoDto.setStName(st.getName());
        return courseBaseInfoDto;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //判断课程id是否为本机构课程
        List<CourseBase> courseBases = courseBaseMapper.selectList(new LambdaQueryWrapper<CourseBase>().eq(CourseBase::getCompanyId, companyId));
        if (!courseBases.isEmpty()){
            for (int i  =0;i<courseBases.size() ;i++) {
                if (editCourseDto.getId().equals(courseBases.get(i).getId())) {
                    break;
                }
                if (i == courseBases.size() - 1) {
                    XueChengPlusException.cast("无法修改非本机构课程");
                }
            }
        }
        //修改CourseBase表
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setChangeDate(LocalDateTime.now());
        //TODO 添加修改人
        //courseBase.setChangePeople();
        int i = courseBaseMapper.updateById(courseBase);
        if (i <= 0){
            throw new RuntimeException("修改失败");
        }
        //修改CourseMarket表
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        courseMarketMapper.updateById(courseMarket);

        //封装信息
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        return courseBaseInfoDto;
    }

    @Transactional
    @Override
    public void deleteCourseBase(Long id) {
        if (id == null){
            XueChengPlusException.cast("参数为空");
        }
        //判断课程审核状态
        if(!courseBaseMapper.selectById(id).getAuditStatus().equals("202002")){
            XueChengPlusException.cast("只有审核状态为“未提交”时才能删除");
        }
        //删除课程
        courseBaseMapper.deleteById(id);
        //删除课程营销信息
        courseMarketMapper.deleteById(id);
        //删除课程计划
        teachplanMapper.delete(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId,id));
        //删除课程媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getCourseId,id));
        //删除课程教师信息
        courseTeacherMapper.delete(new LambdaQueryWrapper<CourseTeacher>().eq(CourseTeacher::getCourseId,id));
    }

    //查询课程信息
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){

        //从课程基本信息表查询
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase==null){
            return null;
        }
        //从课程营销表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //组装在一起
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket!=null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }
        //通过courseCategoryMapper查询分类信息，将分类名称放在courseBaseInfoDto对象
        //课程分类的名称设置到courseBaseInfoDto
        LambdaQueryWrapper<CourseCategory> LambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper.eq(true,CourseCategory::getId,courseBase.getMt());
        CourseCategory courseCategory1 = courseCategoryMapper.selectOne(LambdaQueryWrapper);
        LambdaQueryWrapper<CourseCategory> LambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper2.eq(true,CourseCategory::getId,courseBase.getSt());
        CourseCategory courseCategory2 = courseCategoryMapper.selectOne(LambdaQueryWrapper2);
        courseBaseInfoDto.setMtName(courseCategory1.getName());
        courseBaseInfoDto.setStName(courseCategory2.getName());
        return courseBaseInfoDto;
    }

    //单独写一个方法保存营销信息，逻辑：存在则更新，不存在则添加
    private int saveCourseMarket(CourseMarket courseMarketNew) {
        //参数的合法性校验
        String charge = courseMarketNew.getCharge();
        if (StringUtils.isEmpty(charge)) {
            throw new RuntimeException("收费规则为空");
        }
        //如果课程收费，价格没有填写也需要抛出异常
        if (charge.equals("201001")) {
            if (courseMarketNew.getPrice() == null || courseMarketNew.getPrice().floatValue() <= 0) {
//               throw new RuntimeException("课程的价格不能为空并且必须大于0");
                XueChengPlusException.cast("课程的价格不能为空并且必须大于0");
            }
            if (Integer.parseInt(courseMarketNew.getCharge()) < 0) {
//               throw new RuntimeException("课程的价格不能为空并且必须大于0");
                XueChengPlusException.cast("课程的原价格不能为空并且必须大于等于0");
            }
        }
        //从数据库查询营销信息,存在则更新，不存在则添加
        Long id = courseMarketNew.getId();//主键
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if (courseMarket == null) {
            //插入数据库
            int insert = courseMarketMapper.insert(courseMarketNew);
            return insert;
        } else {
            //将courseMarketNew拷贝到courseMarket
            BeanUtils.copyProperties(courseMarketNew, courseMarket);
            courseMarket.setId(courseMarketNew.getId());
            //更新
            int i = courseMarketMapper.updateById(courseMarket);
            return i;
        }

    }
}
